#include "CONFIG.h"
#include "user.h"
#include <stdio.h>



KeyEvent Key_Flag;
SysPraStr gSYS;

//unsigned int timer_count = 0;
unsigned int key_ok_count = 0;  //长短按判断计数用

unsigned short count;
unsigned char  m=0x9C ;
double  gain=1;
uint8 delaytime;

unsigned int powerOffcount = 0;     //自动关机时间计数用
uint8_t KEYLAST = 1;    //自动关机中用来写入上次按键的状态
uint8_t ROTATE = 0;     //自动关机中用来读取本次旋钮的状态
uint8_t LASTROTATE = 0; //自动关机中用来写入上次旋钮的状态

MenuItemStr* pMenuMain;             // 主界面
MenuItemStr Menu2Set;               //一级设置界面
MenuItemStr Menu3MoreSet;           //二级更多设置
MenuItemStr Menu3BlueTooth;         //蓝牙开关
MenuItemStr Menu3Information;       //二级相关信息
MenuItemStr Menu4SoftWare;          //手机软件
MenuItemStr Menu4SetOffTime;        //自动关机时间
MenuItemStr Menu4SetFlag;           //开机标志
MenuItemStr Menu4SetBuzzer;         //蜂鸣器开关
MenuItemStr Menu4InfoProductP1;     //产品信息 1页
MenuItemStr Menu4InfoProductP2;     //产品信息2页
MenuItemStr Menu4InfoImportantP1;   //重要信息1页
MenuItemStr Menu4InfoImportantP2;   //重要信息2页
MenuItemStr Menu4InfoWarrantyP1;    //有关保修1页
MenuItemStr Menu4InfoWarrantyP2;    //有关保修2页


int user()
{

    PFIC_EnableIRQ(GPIO_A_IRQn);    //开启旋转编码器中断

//    menutest();

    switch(gSYS.SysState){ //判断系统状态

        case 0:{    //0测量界面
            if(delaytime == 80){    //当数值重读时刷新界面
                gSYS.NeedReFreshOLED = 1;
                gSYS.glossNum = Glossiness_VALUE();
            }

            if(gSYS.NeedReFreshOLED){   //刷新屏幕显示内容
                MainMenu1();
                gSYS.NeedReFreshOLED = 0;
            }

            if (gSYS.ShowLogo==1 && gSYS.sysOn != 1) {    //如果没有开机标志 延时消抖
                DelayMs(1000);
                Key_Flag = NoPress;
                gSYS.sysOn = 1;
            }

            if(Key_Flag == ShortPress){     //侦测到短按 切换系统状态到1设置状态
                Key_Flag = NoPress;
                gSYS.SysState = 1;
                gSYS.NeedReFreshOLED = 1;
                gSYS.whichChoose = 1;
                OLED_Clear();
            }
            if(Key_Flag == LongPress){   //侦测到长float receive()按 关机
                gSYS.SysState = 3;
            }
        }break;

        case 1:{    //1设置界面
            if(pMenuMain != NULL){      //设置界面指针
                pMenuMain->MenuRun();
            }else{
                gSYS.SysState = 0;      //空指针异常处理
            }
            if(Key_Flag == LongPress){
                gSYS.SysState = 4;
            }
        }break;

        case 2:{    //2开机LOGO
            if(gSYS.ShowLogo == 2){ //如果需要显示开机LOGO
                if(gSYS.NeedReFreshOLED){   //只运行一次
                    OLED_DrawBMP(0, 0, 128, 8, BMP3);
                    gSYS.NeedReFreshOLED = 0;
                    DelayMs(1000);    // 时延 消抖
                    Key_Flag = NoPress;
                    gSYS.sysOn = 1;
                }
                if(Key_Flag == ShortPress){    //侦测到按键事件后跳出到测量界面
                    Key_Flag = NoPress;
                    gSYS.SysState = 0;
                    gSYS.NeedReFreshOLED = 1;
                    OLED_Clear();
                }
            }else{  //不需要显示的话直接进入测量界面
                gSYS.SysState = 0;
            }
        }break;

        case 3:{    //3关机状态
            if(gSYS.sysOn == 1){
                OLED_DrawBMP(0, 0, 128, 8, BMP4);
                gSYS.sysOn = 0;
                WRITEEEPROM();
            }
            DelayMs(1000);
            OLED_Clear();
            POWER_OFF;
        }break;

//        case 4:{    //开发者模式
//            if(gSYS.NeedReFreshOLED == 1){
//                gSYS.NeedReFreshOLED = 0;
//                MenuDeveloperMode();
//            }
//            if(Key_Flag == ShortPress){
//                if(gSYS.DeveloperMode <= 5){
//                    gSYS.DeveloperMode += 1;
//                }else if(gSYS.DeveloperMode == 5){
//                    gSYS.DeveloperMode += 1;
//                    gSYS.NeedReFreshOLED = 1;
//                    OLED_Clear();
//                    DelayMs(500);
//                }else if(gSYS.DeveloperMode == 6){
//                    gSYS.receive1 = 60;
//                    DelayMs(1000);
//                    gSYS.NeedReFreshOLED = 1;
//                    gSYS.DeveloperMode += 1;
//                }else if(gSYS.DeveloperMode == 7){
//                    gSYS.receive2 = 1270;
//                    DelayMs(1000);
//                    gSYS.NeedReFreshOLED = 1;
//                    gSYS.DeveloperMode += 1;
//                }
//            }
//            if((Key_Flag == ShortPress) && (gSYS.DeveloperMode <= 4)){
//                gSYS.DeveloperMode += 1;
//            }
//            if(gSYS.DeveloperMode == 5){
//                gSYS.NeedReFreshOLED = 1;
//
//            }
//        }break;

        default:{   //异常处理 回到测量界面
            gSYS.SysState=0;
        }break;
    }
    return 0;
}

void Spi0_Init(void)    //SPI初始化
{
     SPI0_MasterDefInit();
     SPI0_CLKCfg(2);
     SPI0_DataMode(Mode3_HighBitINFront);
}

void Timer_0_Init(void)
{
     TMR0_ITCfg(ENABLE, TMR0_3_IT_CYC_END); // 开启中断
     PFIC_EnableIRQ(TMR0_IRQn);
     TMR0_TimerInit(4000);         // 设置定时时间 1ms
     PFIC->IPRIOR[16]=0xff;
}

__INTERRUPT
__HIGH_CODE
void TMR0_IRQHandler(void)  //TMR0 定时中断
{

    if(TMR0_GetITFlag(TMR0_3_IT_CYC_END))
    {
        TMR0_ClearITFlag(TMR0_3_IT_CYC_END);    //清除中断标志
    }

//    timer_count++;
//    if(timer_count==30)
//    {
//        timer_count = 0;
//        TMOS_SystemProcess();
//    }
    if(gSYS.SysState == 1){
        delaytime++;
    }


    if(KEY_OK() != KEYLAST||ROTATE != LASTROTATE){ //判断是否有旋钮和按键的变化，用于自动关机计时
        powerOffcount = 0;
        LASTROTATE = ROTATE;
        KEYLAST = KEY_OK();
    }
    powerOffcount++;
    if((powerOffcount >= (gSYS.SetOffTime*1000*60) )&& gSYS.SysState != 3){
        gSYS.SysState=3;
    }


    if(KEY_OK()== 0){   //按键短按处理   在指定时间内 抬起后发生
        if(key_ok_count >= 50 && key_ok_count< 1000){
            Key_Flag = ShortPress;
        }
        key_ok_count = 0;
    }else {     //按键长按处理，一直按住时发生
        key_ok_count++;
        if(key_ok_count >= 3000){   //按键长按处理
            Key_Flag = LongPress;
        }
    }
}


//中断 旋钮事件
__INTERRUPT
__HIGH_CODE
void GPIOA_IRQHandler(void)
{
//    Key_Flag = NoPress;
    if (GPIOA_ReadITFlagBit(GPIO_Pin_8)) {
        if (GPIOA_ReadPortPin(GPIO_Pin_9)){
            Key_Flag = RightRotate;
            ROTATE += 1;
        }else {
            Key_Flag = LeftRotate;
            ROTATE -= 1;
        }
        GPIOA_ClearITFlagBit(GPIO_Pin_8);//清除中断标志
    }
    if (GPIOA_ReadITFlagBit(GPIO_Pin_9)) {
        if (GPIOA_ReadPortPin(GPIO_Pin_8)){
            Key_Flag = RightRotate;
            ROTATE += 1;
        }else {
            Key_Flag = LeftRotate;
            ROTATE -= 1;
        }
        GPIOA_ClearITFlagBit(GPIO_Pin_9);//清除中断标志
    }
}

float receive(){
    double voltage_mv;
    unsigned char recver[3]={0,0,0};
    unsigned char device_address = 0x90;//从机地址
    unsigned char byte1 ;//高八位
    unsigned char byte2 ;//低八位
    uint16_t result;

    IIC_Init();//I2C初始化


    i2c_tran(device_address,&m,1);//写命令
    if(delaytime == 80){
        i2c_rece(device_address,recver,3);//读数
        delaytime = 0;

        byte1 = recver[0];//高八位
        byte2 = recver[1];//低八位
        count =(unsigned short)((byte1 << 8) | byte2);//高八位低八位放在一个字节里
        voltage_mv=(count*2048)/32767;//电压转换
        voltage_mv/=gain;//除放大倍数
    }


    //判断电压值选择相应的倍数
    if (0 <= voltage_mv && voltage_mv < 256) {
        gain=8;//8倍
        m=0x9F;//1111
    }else if (256 <= voltage_mv && voltage_mv < 512) {
        gain=4;//4倍
        m=0x9E;//1110
    }else if (512 <= voltage_mv && voltage_mv < 1024) {
        gain=2;//2倍
        m=0x9D;//1101
    }else {
        gain=1;//1倍
        m=0x9C;//1100
    }

    return  voltage_mv;
}

uint16_t Glossiness_VALUE(){
    float ADC = receive();
    float result = gSYS.standardK * ADC + gSYS.standardB;
    uint16_t final = (uint16_t)(int)result;
    return final;
}

void menu_init(){
    pMenuMain = &Menu2Set;
    Menu2Set.MenuRun = MenuShowSet2;

    Menu3MoreSet.MenuRun = MenuShowMoreSet3;
    Menu3BlueTooth.MenuRun = MenuShowBlueTooth3;
    Menu3Information.MenuRun = MenuShowInformation3;

    Menu4SoftWare.MenuRun = MenuShowSoftware4;
    Menu4SetOffTime.MenuRun = MenuShowSetoffTime4;
    Menu4SetFlag.MenuRun = MenuShowSetFlag4;
    Menu4SetBuzzer.MenuRun = MenuShowSetBuzzer4;

    Menu4InfoImportantP1.MenuRun = MenuShowInfoImportantP14;
    Menu4InfoImportantP2.MenuRun = MenuShowInfoImportantP24;
    Menu4InfoProductP1.MenuRun = MenuShowInfoProductP14;
    Menu4InfoProductP2.MenuRun = MenuShowInfoProductP24;
    Menu4InfoWarrantyP1.MenuRun = MenuShowInfoWarrantyP14;
    Menu4InfoWarrantyP2.MenuRun = MenuShowInfoWarrantyP24;

}

/*==================================================================
函数名：HandleMenuSwitch
功能：     处理界面切换的修改标志位事件
形参：      MenuItemStr* menu：要切换进入的界面
==================================================================*/
void HandleMenuSwitch(MenuItemStr* menu) {
    Key_Flag = NoPress;
    gSYS.whichChoose = 1;
    gSYS.NeedReFreshOLED = 1;
    OLED_Clear();
    pMenuMain = menu;
}

/*==================================================================
函数名：HandlerEncoderChoose
功能：     根据旋转编码器调整选择项，并在范围内循环
形参：      uint8_t max：循环范围
==================================================================*/
void HandlerEncoderChoose(uint8_t max){
    gSYS.NeedReFreshOLED = 1;
    if(Key_Flag == RightRotate){
        gSYS.whichChoose +=1;
    }else{
        gSYS.whichChoose -= 1;
    }
    if (gSYS.whichChoose > max) {
        gSYS.whichChoose = 1;  // 如果超出最大值，回到 1
    } else if (gSYS.whichChoose < 1) {
        gSYS.whichChoose = max;  // 如果小于 1，设置为最大值
    }
    Key_Flag = NoPress;
}

/*==================================================================
函数名：MenuShow系列函数
功能：     在界面中刷新显示内容，包含按键逻辑关系在内
                    用于pMenuMain.MenuRun。
==================================================================*/
void MenuShowSet2()     //设置主页
{
    if(gSYS.NeedReFreshOLED){  //在需要时进行屏幕刷新
        MenuSet2();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag==LeftRotate || Key_Flag == RightRotate){    //判断旋钮旋转方向
        HandlerEncoderChoose(5);
    }else if(Key_Flag == ShortPress){
        switch(gSYS.whichChoose){
            case 1:{    //语言修改
                Key_Flag = NoPress;
                gSYS.language = !gSYS.language;
                gSYS.NeedReFreshOLED = 1;
                WRITEEEPROM();
                OLED_Clear();
            }break;
            case 2:{    //更多设置
                HandleMenuSwitch(&Menu3MoreSet);
            }break;
            case 3:{    //蓝牙开关
                HandleMenuSwitch(&Menu3BlueTooth);
                gSYS.whichChoose = gSYS.BLon;   //进入蓝牙界面后设置循环位置为当前蓝牙状态
            }break;
            case 4:{    //相关信息
                HandleMenuSwitch(&Menu3Information);
            }break;
            case 5:{    //返回测量界面
                Key_Flag = NoPress;
                gSYS.NeedReFreshOLED = 1;
                gSYS.SysState = 0;
                OLED_Clear();
            }break;
        }
    }
}

void MenuShowMoreSet3()     //更多设置
{
    if(gSYS.NeedReFreshOLED){  //在需要时进行屏幕刷新
        MenuMoreSet3();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag==LeftRotate || Key_Flag == RightRotate)    //判断旋钮旋转方向
    {
        HandlerEncoderChoose(5);
    }else if(Key_Flag == ShortPress){
        switch(gSYS.whichChoose){
            case 1:{    //手机软件
                HandleMenuSwitch(&Menu4SoftWare);
            }break;
            case 2:{    //关机时间
                HandleMenuSwitch(&Menu4SetOffTime);
                gSYS.whichChoose = gSYS.SetOffTime;
//                SetOffTime();
                gSYS.confirm = 1;
            }break;
            case 3:{    //开机标志
                HandleMenuSwitch(&Menu4SetFlag);
                gSYS.whichChoose = gSYS.ShowLogo;   //进入标志界面后设置循环位置为当前标志状态
            }break;
            case 4:{    //蜂鸣器开关
                HandleMenuSwitch(&Menu4SetBuzzer);
            }break;
            case 5:{    //返回设置主页
                HandleMenuSwitch(&Menu2Set);
            }break;
        }
    }
}

void MenuShowBlueTooth3()   //蓝牙开关
{
    if(gSYS.NeedReFreshOLED){  //在需要时进行屏幕刷新
        MenuSetBluetooth3();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == RightRotate || Key_Flag == LeftRotate){    //判断旋钮旋转方向
        HandlerEncoderChoose(2);

    }else if(Key_Flag == ShortPress){   //短按后返回设置主页
        gSYS.BLon = gSYS.whichChoose;   //切换蓝牙状态为当前所指位置
        WRITEEEPROM();
        HandleMenuSwitch(&Menu2Set);
    }
}

void MenuShowInformation3()     //相关信息
{
    if(gSYS.NeedReFreshOLED){  //在需要时进行屏幕刷新
        MenuInformation3();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == RightRotate || Key_Flag == LeftRotate){    //判断旋钮旋转方向
        HandlerEncoderChoose(5);
    }else if(Key_Flag == ShortPress){
        switch(gSYS.whichChoose){
            case 1:{    //产品说明
                HandleMenuSwitch(&Menu4InfoProductP1);
            }break;
            case 2:{    //重要提示
                HandleMenuSwitch(&Menu4InfoImportantP1);
            }break;
            case 3:{    //有关保修
                HandleMenuSwitch(&Menu4InfoWarrantyP1);
            }break;
            case 4:{    //产品信息 无内容，继续显示此页面
                HandleMenuSwitch(&Menu3Information);
            }break;
            case 5:{    //返回设置主页
                HandleMenuSwitch(&Menu2Set);
            }break;
        }
    }
}

void MenuShowSoftware4()    //手机软件
{
    if(gSYS.NeedReFreshOLED){  //在需要时进行屏幕刷新
        MenuSoftware4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == ShortPress){     //短按返回更多设置
        HandleMenuSwitch(&Menu3MoreSet);
    }
}

void MenuShowSetoffTime4()  //关机时间
{
    if(gSYS.NeedReFreshOLED){  //在需要时进行屏幕刷新
        MenuSetOffTime4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == ShortPress){
        Key_Flag = NoPress;
        gSYS.NeedReFreshOLED = 1;
        gSYS.confirm += 1;
    }else if((Key_Flag == LeftRotate || Key_Flag == RightRotate) && gSYS.confirm == 1){
        HandlerEncoderChoose(20);
        gSYS.SetOffTime = gSYS.whichChoose;
    }
    if(gSYS.confirm == 3){
        gSYS.SetOffTime = gSYS.whichChoose;
        WRITEEEPROM();
        HandleMenuSwitch(&Menu3MoreSet);
    }
}

void MenuShowSetFlag4()
{
    if(gSYS.NeedReFreshOLED){  //在需要时进行屏幕刷新
        MenuSetFlag4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == RightRotate || Key_Flag == LeftRotate){    //判断旋钮旋转方向
        HandlerEncoderChoose(2);
    }else if(Key_Flag == ShortPress){   //短按后返回更多设置
        gSYS.ShowLogo = gSYS.whichChoose;   //切换开机标志状态为当前所指位置
        WRITEEEPROM();
        HandleMenuSwitch(&Menu3MoreSet);
    }
}

void MenuShowSetBuzzer4()
{
    if(gSYS.NeedReFreshOLED){
        MenuSetBuzzer4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == ShortPress){
        HandleMenuSwitch(&Menu3MoreSet);
    }
}

void MenuShowInfoProductP14()
{
    if(gSYS.NeedReFreshOLED){
        MenuInfoProduct1Page4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == LeftRotate || Key_Flag == RightRotate){
        Key_Flag = NoPress;
        gSYS.NeedReFreshOLED = 1;
        OLED_Clear();
        pMenuMain = &Menu4InfoProductP2;
    }
    if(Key_Flag == ShortPress){
        HandleMenuSwitch(&Menu3Information);
    }
}

void MenuShowInfoProductP24()
{
    if(gSYS.NeedReFreshOLED){
        MenuInfoProduct2Page4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == LeftRotate || Key_Flag == RightRotate){
        Key_Flag = NoPress;
        gSYS.NeedReFreshOLED = 1;
        OLED_Clear();
        pMenuMain = &Menu4InfoProductP1;
    }
    if(Key_Flag == ShortPress){
        HandleMenuSwitch(&Menu3Information);
    }
}

void MenuShowInfoImportantP14()
{
    if(gSYS.NeedReFreshOLED){
        MenuInfoImportant1Page4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == LeftRotate || Key_Flag == RightRotate){
        Key_Flag = NoPress;
        gSYS.NeedReFreshOLED = 1;
        OLED_Clear();
        pMenuMain = &Menu4InfoImportantP2;
    }
    if(Key_Flag == ShortPress){
        HandleMenuSwitch(&Menu3Information);
    }
}

void MenuShowInfoImportantP24()
{
    if(gSYS.NeedReFreshOLED){
        MenuInfoImportant2Page4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == LeftRotate || Key_Flag == RightRotate){
        Key_Flag = NoPress;
        gSYS.NeedReFreshOLED = 1;
        OLED_Clear();
        pMenuMain = &Menu4InfoImportantP1;
    }
    if(Key_Flag == ShortPress){
        HandleMenuSwitch(&Menu3Information);
    }
}

void MenuShowInfoWarrantyP14()
{
    if(gSYS.NeedReFreshOLED){
        MenuInfoWarranty1Page4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == LeftRotate || Key_Flag == RightRotate){
        Key_Flag = NoPress;
        gSYS.NeedReFreshOLED = 1;
        OLED_Clear();
        pMenuMain = &Menu4InfoWarrantyP2;
    }
    if(Key_Flag == ShortPress){
        HandleMenuSwitch(&Menu3Information);
    }
}

void MenuShowInfoWarrantyP24()
{
    if(gSYS.NeedReFreshOLED){
        MenuInfoWarranty2Page4();
        gSYS.NeedReFreshOLED = 0;
    }
    if(Key_Flag == LeftRotate || Key_Flag == RightRotate){
        Key_Flag = NoPress;
        gSYS.NeedReFreshOLED = 1;
        OLED_Clear();
        pMenuMain = &Menu4InfoWarrantyP1;
    }
    if(Key_Flag == ShortPress){
        HandleMenuSwitch(&Menu3Information);
    }
}
